
const config = require("../config");

var Net = (function () {
    function Net() {
        this.requests = [];
        this.loading = false;
        this.logining = false;
        this.numLoginRetry = 5;//登录重试次数
        this.numRequestRetry = 5;//请求重试次数
        this.requireLogin = false;//是否需要用户登录
    }
    /**
     * 用户登录
     */
    Net.prototype.login = function (success,refuse) {
        if (this.isLogin()) if(success)success();
        if (this.logining) return;
        this.logining = true;
        var obj = this;
        var doLogin = function (login_info, user_info) {
            console.log(login_info, user_info);
            wx.request({
                url: config.login.url,
                method: 'GET',
                header: { 'Code': login_info.code, 'Encrypted-Data': user_info.encryptedData, 'IV': user_info.iv },
                success: function (res) {

                    if (res.data.sid) {
                        wx.setStorageSync('sid', res.data.sid);
                        wx.setStorageSync('user', user_info.userInfo);

                        console.log(res.data);
                        if (success) success();
                        obj.logining = false;
                        console.log("登录成功");
                    } else {
                        if (obj.numLoginRetry > 0) {
                            obj.numLoginRetry--;
                            doLogin(login_info, user_info);
                            console.warn("无法获取登录信息，正在重试" + obj.numLoginRetry);;
                        } else {
                            console.warn("无法登录");;
                        }
                    }
                },
                fail: function () {
                    if (obj.numLoginRetry > 0) {
                        obj.numLoginRetry--;
                        doLogin(login_info, user_info);
                        console.warn("无法登录，正在重试" + obj.numLoginRetry);;
                    } else {
                        console.warn("无法登录");;
                    }

                },
            })
        }
        //调用微信登录接口
        wx.login({
            success: function (login_info) {
                var code = login_info.code;
                if (!code) {
                    console.warn("无法获取code");
                    return;
                }
                //获取用户基本信息
                wx.getUserInfo({
                    success: function (user_info) {
                        doLogin(login_info, user_info);
                    },
                    fail: function () {
                        console.warn("无法获取用户信息");
                        obj.requests=[];
                        obj.loading=false;
                        obj.logining=false;
                        typeof refuse=='function' && refuse();
                    },
                })
            },
            fail: function () {
                console.warn("请点击允许");
                obj.requests=[];
                obj.loading=false;
                obj.logining=false;
            },
        });

    }
    Net.prototype.isLogin = function () {
        return wx.getStorageSync('sid');
    }

    Net.prototype.request = function (cfg) {
        var obj = this;
        let options = { method: "GET", data: {} };
        for (var k in cfg) {
            options[k] = cfg[k];
        }

        var r = function () {
            obj.loading = true;
            wx.request({
                url: options.url,
                data: options.data,
                method: options.method,
                header: { sid: wx.getStorageSync('sid') },
                success: function (res) {
                    if (res.data.status) {
                        if (res.data.status == 401) {
                            wx.removeStorageSync('sid');
                            if (obj.numRequestRetry <= 0) {
                                return;
                            }
                            obj.numRequestRetry--;
                            obj.request(cfg);
                        }
                    } else {
                        obj.loading = false;
                        obj.startRequest();
                        // if (options.success) options.success(res);
                        typeof options.success === 'function' && options.success(res);
                    }
                },
                fail: function () {
                    console.log('请求失败');
                    typeof options.fail === 'function' && options.fail();
                }
            })
        }
        
        if (options.requireLogin === true) {
            if(this.isLogin()){
                r();
                return;
            }
            this.login(function () {
                r();
            },options.refuse);
        } else {
            r();
        }
    }

    Net.prototype.startRequest = function () {
        if (this.loading || this.logining || this.requests.length == 0) {
            return;
        }
        this.request(this.requests.shift());
    }
    Net.prototype.post = function (cfg) {
        cfg.method = "POST";
        this.requests.push(cfg);
        this.startRequest();
    }
    Net.prototype.get = function (cfg) {
        
        cfg.method = "GET";
        this.requests.push(cfg);
        this.startRequest();
    }

    return Net;
})();

var net = new Net();
module.exports = {
    get: function (cfg) {
        net.get(cfg);
    },
    post: function (cfg) {
        net.post(cfg);
    },
    isLogin:net.isLogin,
}